package io.hilo.example.demo.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.hilo.boot.core.UT;
import org.hilo.boot.core.xss.XssHttpServletRequestWrapper;
import io.hilo.example.demo.service.GeneratorService;

/**
 * Controller Demo
 * 
 * @author zollty
 * @since 2018-3-12
 */
@Controller
@RequestMapping("/app/gen")
public class GeneratorController {
    
    @Autowired
    private GeneratorService generatorService;
    
    /**
     * 生成代码
     */
    @RequestMapping(value = "/by-type", method= {RequestMethod.POST, RequestMethod.GET})
    public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取表名，不进行xss过滤
        HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);
        String useType = orgRequest.getParameter("useType");
        if(UT.Str.isBlank(useType)) {
            return;
        }
        String groupId = orgRequest.getParameter("groupId");
        String artifactId = orgRequest.getParameter("artifactId");
        String basePackage = orgRequest.getParameter("basePackage");
        if(UT.Str.isBlank(groupId)) {
            groupId = "com.zollty.hilo";
        }
        if(UT.Str.isBlank(artifactId)) {
            artifactId = "project";
            if(UT.Str.isBlank(basePackage)) {
                basePackage = groupId + artifactId;
            }
        }

        byte[] data = generatorService.generatorCode(useType, groupId, artifactId, basePackage);
        if (data == null) {
            return;
        }

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\""+artifactId+".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

}
